package org.example.pims.security.service;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author bothin
 */
public class LoginAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    public LoginAuthenticationProvider(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        UserDetails userDetails = this.userDetailsService.loadUserByUsername(authentication.getName());
        String credential = (String) authentication.getCredentials();
        if (new BCryptPasswordEncoder().matches(credential,userDetails.getPassword())){
            return new UsernamePasswordAuthenticationToken(userDetails,
                    authentication.getCredentials(), userDetails.getAuthorities());
        }

        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
